﻿#define DEBUG

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using TERP.WaterClient.DbServices;
using TERP.WaterClient.Views.Common;
using System.Data;
using System.Security.Cryptography;
using System.IO;
using System.Globalization;
using System.Reflection;

namespace TERP.WaterClient.Common
{
    public class Util
    {
        private const string TITLE_INFO_BOX = "Thông báo";
        private const string TITLE_ERR_BOX = "Lỗi";

		/// <summary>
		/// 
		/// </summary>
		/// <param name="msg"></param>
        public static void WriteLine(string msg){
            #if (DEBUG)
                Console.WriteLine("=== DEBUG ===" + msg);
            #endif
        }

		public static bool IsStringEmpty(string str)
		{
			return (str != null && str.Trim().Length == 0);
		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lstStr"></param>
        /// <returns></returns>
        public static string StretchListString(List<string> lstStr)
        {
            StringBuilder strBuider = new StringBuilder();
            foreach (string str in lstStr)
            {
                strBuider.Append(str).Append("|");
            }
            string strResult = strBuider.ToString();
            strResult = strResult.Substring(0, strResult.Length - 1);
            return strResult;
        }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static DateTime GetDateTimeValue(object obj)
		{
			if (obj == DBNull.Value){
				return DateTime.MinValue;
			}
			DateTime dtReturn;
			if (DateTime.TryParse(obj.ToString(), out dtReturn))
				return dtReturn;
			else
				return DateTime.MinValue;

		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="dtbl"></param>
		public static void UpcaseColumnName(DataTable dtbl){
			if (dtbl == null)
				return;
			foreach (DataColumn dtCol in dtbl.Columns){
				string tmp = dtCol.ColumnName;
				dtCol.ColumnName = tmp.ToUpper();
			}
		}

		public static bool IsExitsColumnNameInDataTable(DataTable dtbl, string strColumnName)
		{
			if (dtbl == null)
				return false;
			foreach (DataColumn dtCol in dtbl.Columns)
			{
				if (dtCol.ColumnName.Equals(strColumnName))
				{
					return true;
				}
			}
			return false;
		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsUrlAvailable(string url)
        {
            if (url == null || url.Trim().Equals(""))
                return false;
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

                using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
                {
                    if (rsp.StatusCode == HttpStatusCode.OK)
                    {
                        return true;
                    }
                }
            }
            catch (Exception)
            {
            }
            return false;
        }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ex"></param>
		public static void ShowExceptionBox(Exception ex){
			ShowExceptionBox(TITLE_ERR_BOX,ex);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ex"></param>
		public static void ShowExceptionBox(string title, Exception ex)
		{
			if (ex is ServiceException)
			{
                ServiceException sex = (ServiceException)ex;
                FrmErrorMessage frm = new FrmErrorMessage();
                frm.Text = title;
                string msgCode = sex.ErrorMessage;
                string msgValue = ErrorMsgHandler.Instance.GetMessage(msgCode);
                frm.SetErrorMessage(msgValue, sex.ErrorDetail);
                frm.ShowDialog();
			}
			else
			{
				MessageBox.Show(ex.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}

        public static void ShowMessageBox(string msg){
			MessageBox.Show(msg, TITLE_INFO_BOX, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void ShowErrorMsgBox(string msg){
            MessageBox.Show(msg, TITLE_ERR_BOX, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static bool ShowMessageBoxQuestion(string msg)
        {
           if(( MessageBox.Show(msg, TITLE_INFO_BOX, MessageBoxButtons.OKCancel, MessageBoxIcon.Information)==DialogResult.OK))
           {
               return true;
           }
           return false;
        }

        public static bool ShowMsgBoxWarningQuestion(string msg)
        {
            if ((MessageBox.Show(msg, TITLE_INFO_BOX, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK))
            {
                return true;
            }
            return false;
        }

		public static void ShowErrorMsgBox(string title, string msg)
		{
			MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

        public static void ShowWarningMsgBox(string msg)
        {
            MessageBox.Show(msg, TITLE_INFO_BOX, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static void ShowWarningMsgBox(string title, string msg)
        {
            MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //Isnumeric
        public static bool IsNumeric(object obj)
        {
            if (obj == null)
            {
                return false;
            }
            else
            {
                double OutValue;
                return double.TryParse(obj.ToString().Trim(),
                 System.Globalization.NumberStyles.Any,
                   System.Globalization.CultureInfo.CurrentCulture,
                   out OutValue);
            }
        }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static bool IsInteger(object obj)
		{
			if (obj == null)
			{
				return false;
			}
			else
			{
				int outValue;
				string strValue = Convert.ToString(obj).Trim();
				return Int32.TryParse(strValue, out outValue);
			}
		}

        //Is datetime

        public static bool IsDateTime(object Object)
        {
            string strDate = Object.ToString();
            try
            {

                DateTime dt;
                DateTime.TryParse(strDate,
                    System.Globalization.CultureInfo.CurrentCulture,
                    System.Globalization.DateTimeStyles.None, out dt);

                if (dt > DateTime.MinValue && dt < DateTime.MaxValue)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }
        //Standard string
        public static string StandardizedString(object Object)
        {
            string str = Object.ToString().Trim();
            string s1 = "  ", s2 = " ";
            while (str.Contains(s1))
            {
                str = str.Replace(s1, s2);
            }
            return str;
        }
        //Convert FormatDatetime
        public static string FormatDate(object objDate)
        {
            try
            {
                return DateTime.Parse(objDate.ToString()).ToString("MM/dd/yyyy");
            }
            catch
            {
                return DateTime.MinValue.ToString("MM/dd/yyyy");
            }
        }
        //
        public static int GetIndexOfColByFieldName(System.Data.DataTable dt, string sFieldName)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].ColumnName.Equals(sFieldName))
                    return i;
            }
            return Int32.MinValue;
        }

        /// <summary>
        /// Hàm Convert IEnumerable to DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IEnumerable<T> items)
        {
            var tb = new DataTable(typeof(T).Name);
            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var prop in props)
            {
                Type pt = prop.PropertyType;
                if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
                    pt = Nullable.GetUnderlyingType(pt);

                tb.Columns.Add(prop.Name, pt);
            }
            foreach (var item in items)
            {
                var values = new object[props.Length];
                for (var i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }
            return tb;
        }

        /// <summary>
        /// read number to string for show in report
        /// </summary>
        /// <param name="err"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string dichso(ref string err, string number)
        {

            double chuso;
            int sovonglap = 0;
            string[] so = new string[10];
            string[] tumuoi = new string[9];
            string[] tuhaimuoi = new string[9];
            string[] group = new string[6];
            string thanhchu = "";
            bool isSoAm = false;
            try
            {
                chuso = Convert.ToDouble(number);
                if (chuso < 0)
                {
                    isSoAm = true;
                    chuso = -chuso;
                }
            }
            catch
            {
                err = "Vui lòng kiểm tra lại giá trị số .";
                return "";
            }
            if (chuso == 0)
            {
                thanhchu = " không ";
            }
            //lay phan nguyen cua so da tinh toan duoc
            double sokytu = Math.Floor(Math.Log10(chuso) + 1);
            double sonhom = Math.Floor((Math.Log10(chuso) + 0.5) / 3 + 1);
            if (sokytu >= 17)
            {
                err = "Dãy số quá dài -Bạn kiểm tra lại";

            }

            so[0] = "một";
            so[1] = "hai";
            so[2] = "ba";
            so[3] = "bốn";
            so[4] = "năm";
            so[5] = "sáu";
            so[6] = "bảy";
            so[7] = "tám";
            so[8] = "chín";
            so[9] = "mười";

            tumuoi[0] = "mười một";
            tumuoi[1] = "mười hai";
            tumuoi[2] = "mười ba";
            tumuoi[3] = "mười bốn";
            tumuoi[4] = "mười năm";
            tumuoi[5] = "mười sáu";
            tumuoi[6] = "mười bảy";
            tumuoi[7] = "mười tám";
            tumuoi[8] = "mười chín";
            //day dem so hai muoi
            tuhaimuoi[0] = "";
            tuhaimuoi[1] = "hai mươi";
            tuhaimuoi[2] = "ba mươi";
            tuhaimuoi[3] = "bốn mươi";
            tuhaimuoi[4] = "năm mươi";
            tuhaimuoi[5] = "sáu mươi";
            tuhaimuoi[6] = "bảy mươi";//100.010.010.001.001
            tuhaimuoi[7] = "tám mươi";
            tuhaimuoi[8] = "chín mươi";

            //khai bao them nhom day so
            group[0] = "nghìn";
            group[1] = "triệu";
            group[2] = "tỷ";

            int k = 0;

            if (chuso > 0)
            {
                for (int i = 0; i < Convert.ToInt64(sonhom); i++)
                {
                    sovonglap = sovonglap + 1;
                    string hangtram = "";
                    string hangchuc = "";
                    string hangdv = "";
                    double sotien = chuso;
                    chuso = Math.Floor(chuso / 1000);
                    double new_number = Math.Floor(sotien - chuso * 1000);
                    //new khac khong thuc hien doc day so
                    if (new_number != 0)
                    {
                        double tram = Math.Floor(new_number / 100);
                        double chuc = Math.Floor((new_number - tram * 100) / 10);
                        double donvi = right(new_number, 1);
                        if (tram != 0)
                        {
                            hangtram = so[Convert.ToInt32(tram - 1)] + " trăm";
                        }
                        else
                        {
                            if (sovonglap < Convert.ToInt32(sonhom) && chuc != 0)
                            {
                                hangtram = "không trăm ";
                            }
                        }
                        if (chuc != 0)
                        {
                            if (chuc != 1)
                            {
                                hangchuc = tuhaimuoi[Convert.ToInt32(chuc - 1)];
                            }
                            else
                            {
                                hangchuc = so[9];
                            }
                            if (donvi != 0 && chuc != 1)
                            {
                                hangchuc = tuhaimuoi[Convert.ToInt32(chuc - 1)];
                                //hang don vi =5 doc la lam
                                //if(donvi != 5) 
                                //{
                                //    hangdv = so[Convert.ToInt32(donvi-1)];//mot tram hai muoi;
                                //}
                                //else 
                                //{
                                //    hangdv = "lăm";
                                //}

                                switch (donvi.ToString())
                                {
                                    case "4":
                                        hangdv = "tư";
                                        break;
                                    case "5":
                                        hangdv = "lăm";
                                        break;
                                    case "1":
                                        hangdv = "mốt";
                                        break;
                                    default:
                                        hangdv = so[Convert.ToInt32(donvi - 1)];//mot tram hai muoi;
                                        break;
                                }

                            }
                            //hang chuc =1 hang don vi khac 0
                            if (donvi != 0 && chuc == 1)
                            {
                                if (Math.Abs(sotien) > 100)
                                {
                                    hangchuc = tumuoi[Convert.ToInt32(donvi - 1)];
                                }
                                else
                                {
                                    hangchuc = tumuoi[Convert.ToInt32(donvi - 1)];
                                }
                            }
                            if (donvi == 0)
                            {
                                hangdv = "";
                            }
                        }
                        //het phan hang chuc khac 0
                        else
                        {
                            if (donvi != 0)
                            {
                                if (new_number > 9)
                                {
                                    if (i == 0 && tram == 0)
                                    {
                                        //hangchuc = "lẻ";
                                        hangchuc = "";
                                        hangdv = so[Convert.ToInt32(donvi - 1)];
                                    }
                                    else
                                    {
                                        hangchuc = "linh";
                                        hangdv = so[Convert.ToInt32(donvi - 1)];
                                    }
                                }
                                else
                                {
                                    if (i == 0 && tram == 0)
                                    {
                                        //hangchuc = "lẻ";
                                        hangchuc = "";
                                        hangdv = so[Convert.ToInt32(donvi - 1)];
                                    }
                                    else
                                    {
                                        hangchuc = "";
                                        hangdv = so[Convert.ToInt32(donvi - 1)];
                                    }
                                }
                            }
                            else
                            {
                                hangchuc = "";
                                hangdv = "";
                            }
                        }
                        if (k == 0)
                        {
                            thanhchu = hangtram.Trim() + IIF(hangchuc.Trim() != "", " ", "") + hangchuc.Trim() + IIF(hangdv.Trim() != "", " ", "") + hangdv.Trim();
                        }
                        else
                        {
                            thanhchu = hangtram.Trim() + " " + hangchuc.Trim() + IIF(hangchuc.Trim() != "", " ", "") + hangdv.Trim() + IIF(hangdv.Trim() != "", " ", "") + group[Convert.ToInt32(k - 1)].Trim() + " " + thanhchu.Trim();
                        }
                    }
                    if (new_number == 0 && i * 4 == 12)
                    {
                        thanhchu = hangtram.Trim() + " " + hangchuc.Trim() + IIF(hangchuc.Trim() != "", " ", "") + hangdv.Trim() + IIF(hangdv.Trim() != "", " ", "") + group[2].Trim() + " " + thanhchu.Trim();
                    }

                    if (k < 3)
                    {
                        k = k + 1;
                    }
                    else
                    {
                        k = 1;
                    }
                }
            }
            if (isSoAm)
            {
                thanhchu = "âm " + thanhchu;
            }
            string chudau = thanhchu.Trim().Substring(0, 1);
            string cuoi = thanhchu.Trim().Substring(1, thanhchu.Trim().Length - 1);
            chudau = chudau.Trim().ToUpper();
            thanhchu = chudau + cuoi;
            return thanhchu + " đồng . /.";
        }
        public static object IIF(bool x1, object x2, object x3)
        {
            if (x1 == true)
            {
                return x2;
            }
            else
            {
                return x3;
            }
        }

        //tao ham lay so ben phai.
        public static double right(double value1, int numb)
        {
            string value2 = Convert.ToString(value1);
            if (value2.Length < numb)
            {
                return Convert.ToDouble(value2);
            }
            return Convert.ToDouble(value2.Substring(value2.Length - numb));
        }

		public static string SinhMa(string ma)
		{
			DateTime mydate = DateTime.Now;
			string myID = ma + "-" + mydate.ToString("yyMMdd-hhmmss");
			return myID;
		}

		public static DateTime GetDateFirstOfCurrentMonth(DateTime dtNow)
		{
			return new DateTime(dtNow.Year, dtNow.Month, 1);
		}
    }
}
